#include "include/user_account.hpp"

// Position类方法实现
double Position::getTotalCost() const { return shares * avgPrice; }

double Position::getCurrentValue() const { return shares * currentPrice; }

double Position::getProfit() const {
  return getCurrentValue() - getTotalCost();
}

double Position::getProfitPercent() const {
  if (getTotalCost() == 0)
    return 0;
  return (getProfit() / getTotalCost()) * 100.0;
}

// UserAccount类实现
UserAccount::UserAccount(const QString &username, double initialBalance)
    : m_username(username), m_balance(initialBalance) {}

QString UserAccount::getUsername() const { return m_username; }

double UserAccount::getBalance() const { return m_balance; }

void UserAccount::setBalance(double balance) { m_balance = balance; }

bool UserAccount::buy(const QString &stockCode, const QString &stockName,
                      int shares, double price) {
  double totalCost = shares * price;

  // 检查余额是否足够
  if (m_balance < totalCost) {
    return false;
  }

  // 扣减余额
  m_balance -= totalCost;

  // 更新或添加持仓
  Position *pos = getPosition(stockCode);
  if (pos) {
    // 现有持仓，更新平均价格
    double newTotalValue = pos->shares * pos->avgPrice + shares * price;
    pos->shares += shares;
    pos->avgPrice = newTotalValue / pos->shares;
    pos->currentPrice = price; // 更新当前价格
  } else {
    // 新增持仓
    m_positions.append({stockCode, stockName, shares, price, price});
  }

  // 添加交易记录
  m_transactionHistory.append(TransactionRecord(
      stockCode, stockName, TransactionRecord::Type::Buy, shares, price));

  return true;
}

bool UserAccount::sell(const QString &stockCode, const QString &stockName,
                       int shares, double price) {
  // 检查是否有足够的股票可卖
  Position *pos = getPosition(stockCode);
  if (!pos || pos->shares < shares) {
    return false;
  }

  // 增加余额
  double totalRevenue = shares * price;
  m_balance += totalRevenue;

  // 更新持仓
  pos->shares -= shares;

  // 如果股数为0，则从持仓列表中删除
  if (pos->shares == 0) {
    for (int i = 0; i < m_positions.size(); ++i) {
      if (m_positions[i].stockCode == stockCode) {
        m_positions.removeAt(i);
        break;
      }
    }
  }

  // 添加交易记录
  m_transactionHistory.append(TransactionRecord(
      stockCode, stockName, TransactionRecord::Type::Sell, shares, price));

  return true;
}

QVector<Position> &UserAccount::getPositions() { return m_positions; }

const QVector<Position> &UserAccount::getPositions() const {
  return m_positions;
}

Position *UserAccount::getPosition(const QString &stockCode) {
  for (auto &pos : m_positions) {
    if (pos.stockCode == stockCode) {
      return &pos;
    }
  }
  return nullptr;
}

void UserAccount::updatePositionPrice(const QString &stockCode,
                                      double newPrice) {
  Position *pos = getPosition(stockCode);
  if (pos) {
    pos->currentPrice = newPrice;
  }
}

double UserAccount::getTotalAssets() const {
  double totalPositionValue = 0.0;
  for (const auto &pos : m_positions) {
    totalPositionValue += pos.getCurrentValue();
  }
  return m_balance + totalPositionValue;
}

const QVector<TransactionRecord> &UserAccount::getTransactionHistory() const {
  return m_transactionHistory;
}
